package com.xilihui.xlh.core.app;

import android.app.Application;
import android.app.Notification;
import android.content.Context;
import android.os.Process;
import android.support.multidex.MultiDex;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.entity.UMessage;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;
import com.xilihui.xlh.BuildConfig;
import com.xilihui.xlh.R;
import com.xilihui.xlh.business.activitys.LoginActivity;
import com.xilihui.xlh.constant.StrConst;
import com.xilihui.xlh.constant.UmengConst;
import com.xilihui.xlh.core.crash.CrashExceptionHandler;
import com.xilihui.xlh.core.util.LogUtil;
import com.xilihui.xlh.core.util.ProcessUtil;
import com.xilihui.xlh.core.util.SPUtil;
import com.xilihui.xlh.core.util.YEventBuses;

import org.json.JSONException;

import java.util.HashMap;

/**
 * Created by Administrator on 2018/5/15.
 */

public class BaseApplication extends Application{

    private static BaseApplication instance;
    
    public static BaseApplication get(){
        return instance;
    }

    public static RefWatcher getRefWatcher(Context context) {
        BaseApplication application = (BaseApplication) context.getApplicationContext();
        return application.refWatcher;
    }

    private RefWatcher refWatcher;

    //static 代码段可以防止内存泄露
    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.bg, R.color.text);//全局设置主题颜色
                layout.setHeaderHeight(45);
                return new ClassicsHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                layout.setHeaderHeight(45);
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });
    }
    
    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        MultiDex.install(this);
        registerActivityLifecycleCallbacks(ForegroundCallbacks.init(instance));
        initLeakCanary();
        Fresco.initialize(this);
        if(ProcessUtil.isUIProcess(this)){
            initUShare();
            initUAnalysis();
            if(BuildConfig.APP_DEBUG==2||BuildConfig.APP_DEBUG==1){
                initCrash();
            }
        }
        
        initUPush();
        
    }
    
    public void initLeakCanary(){
        if(LeakCanary.isInAnalyzerProcess(this)){
            LogUtil.i("mylog","");
            return;
        }
        refWatcher = LeakCanary.install(this);
    }
    
    public void initCrash(){
        CrashExceptionHandler.getInstance().init();
    }

    /**
     * 初始化
     */
    private void initUShare() {
        // 分享
        UMConfigure.init(this, "5b173ffff43e485c3f000025", "Umeng", UMConfigure.DEVICE_TYPE_PHONE, null);
        UMShareAPI.get(this);
        PlatformConfig.setWeixin(UmengConst.WECHAT_APPKEY, UmengConst.WECHAT_SECRET);
        PlatformConfig.setQQZone(UmengConst.QQ_APPKEY, UmengConst.QQ_SECRET);
    }

    /**
     * 友盟统计
     */
    private void initUAnalysis() {
        // 友盟设置场景类型（普通统计场景类型）
        MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_UM_NORMAL);
        // 禁止默认的页面统计方式，采用Fragment的统计方式
        MobclickAgent.openActivityDurationTrack(false);
        // 日志加密
        MobclickAgent.enableEncrypt(true);
        // 使用测试模式
        MobclickAgent.setDebugMode(BuildConfig.DEBUG);
    }

    /**
     * 初始友盟推送
     */
    private void initUPush(){
        LogUtil.i("mylog","初始化友盟推送");
       
        PushAgent mPushAgent = PushAgent.getInstance(this);
        //注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {
            @Override
            public void onSuccess(String deviceToken) {
                //注册成功会返回device token
                LogUtil.i("mylog","device:"+deviceToken);
                SPUtil.put(getBaseContext(),SPUtil.DEVICE_TOKEN,deviceToken);
            }
            @Override
            public void onFailure(String s, String s1) {
                LogUtil.i("mylog","友盟推送注册失败:"+"s"+s+"s1:"+s1);
            }
        });

        mPushAgent.setMessageHandler(new UmengMessageHandler() {
            @Override
            public Notification getNotification(Context context, UMessage uMessage) {
                String s;
                try {
                    s = uMessage.getRaw().toString(4);
                    LogUtil.i("mylog","umeng:"+s);
                    HashMap<String,String> hashMap = (HashMap<String,String>) uMessage.extra;
//                    String wa_id = hashMap.get("wa_id");
                    String status = hashMap.get("status");
                    YEventBuses.post(new YEventBuses.Event(StrConst.UMENG_PUSH)
                            .setParams(status));
                } catch (JSONException e) {
                    e.printStackTrace();
                    s = "不是Json格式";
                }
                LogUtil.e("UPush", s);
                return super.getNotification(context, uMessage);
            }
        });
        // 友盟推送点击跳转的实现
//        mPushAgent.setNotificationClickHandler(new UPushReceiver());
        
        
    }


    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }
    
}
